import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FitBox'),
        leading: Icon(Icons.menu),
        actions: [Icon(Icons.search), Icon(Icons.settings)],
      ),
      body: FittedBoxTextDemo(),
    );
  }
}

//单行缩放布局

/*
当 Row 没有被 FittedBox 包裹时，此时父组件传给 Row 的约束的 maxWidth 为屏幕宽度，此时，Row 的宽度也就是屏幕宽度，
当被FittedBox 包裹时，FittedBox 传给 Row 的约束的 maxWidth 为无限大（double.infinity），因此Row 的最终宽度就是子组件的宽度之和。

所以当我们有需求希望Row中的内容即要MainAxisAlignment.spaceEvenly的形式显示在屏幕上, 
又不希望溢出时, 可以使用FittedBox来封装一个单行缩放控件, 例如SingleLineFittedBox
*/

class FittedBoxTextDemo extends StatelessWidget {
  const FittedBoxTextDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          //会提示 溢出
          wRow(' 000000000000000000 '),
          //通过FittedBox包裹的控件 会根据
          SingleLineFittedBox(child: wRow(' 9999999999999999999999 ')),
          wRow(' flutter '),
          SingleLineFittedBox(child: wRow(' fultter ')),
        ]
            .map((e) => Padding(
                  padding: EdgeInsets.symmetric(vertical: 5),
                  child: e,
                ))
            .toList(),
      ),
    );
  }

  Widget wRow(String text) {
    Widget child = Text(text);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [child, child, child],
    );
  }
}

class SingleLineFittedBox extends StatelessWidget {
  const SingleLineFittedBox({Key? key, this.child}) : super(key: key);
  final Widget? child;
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      return FittedBox(
        child: ConstrainedBox(
          constraints: constraints.copyWith(
              minWidth: constraints.maxWidth, maxWidth: double.infinity),
          child: child,
        ),
      );
    });
  }
}

class FitBoxDemo extends StatelessWidget {
  const FitBoxDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          _wContainer(BoxFit.none),
          Text('Flutter'),
          _wContainer(BoxFit.contain),
          Text('Flutter 中国')
        ],
      ),
    );
  }

  Widget _wContainer(BoxFit boxFit) {
    return Container(
      width: 50,
      height: 60,
      color: Colors.red,
      child: FittedBox(
        fit: boxFit,
        child: Container(
          width: 80,
          height: 90,
          color: Colors.blue,
        ),
      ),
    );
  }
}
